package org.snusmumr.android.media.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Bits {
	
	/**
	 * Set 0 or 1 depending of <code>value</code> in the position <code>position</code>
	 * of String base. Starting with index 1
	 * @param base - String to set bits
	 * @param position - Position of bits
	 * @param value - if TRUE set 1 otherwise 0
	 * @return Bitmask of type '0101010101'
	 */
	public static final String setBit(String base, int position, boolean value) {
		if(base == null)
			base = "";
		if(position < 1)
			return base;
		
		char[] baseArray = base.toCharArray();
		char[] resultArray;
		if(base.length() >= position)
			resultArray = baseArray;
		else {
			resultArray = new char[position];
			System.arraycopy(baseArray, 0, resultArray, 0, baseArray.length);
			Arrays.fill(resultArray, baseArray.length, resultArray.length, '0');
		}
		
		resultArray[position-1] = value ? '1' : '0';
		return new String(resultArray);
	}
	
	/**
	 * Return true if bit on the position <code>position</code> is set.
	 * Starting with index 1
	 * @param base
	 * @param position
	 * @return TRUE if bit set. Otherwise false
	 */
	public static final boolean isSet(String base, int position) {
		if(Utils.isEmpty(base))
			return false;
		if(position < 1)
			return false;
		if(base.length() < position)
			return false;
		char bit = base.charAt(position-1);
		return bit == '1';
	}
	
	public static final List<Integer> getBits(String base){
		if(Utils.isEmpty(base))
			return new ArrayList<Integer>(0);
		char[] baseArray = base.toCharArray();
		List<Integer> list = new ArrayList<Integer>(baseArray.length);
		for(int i=0; i<baseArray.length; i++) {
			if(baseArray[i] == '1')
				list.add(i+1);
		}
		return list;
	}
}
